package com.java80.littlegame.common.db.dao.cacheImpl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.java80.littlegame.common.cache.CacheService;
import com.java80.littlegame.common.db.dao.URoomInfoDao;
import com.java80.littlegame.common.db.dao.dbImpl.URoomInfoDaoDBImpl;
import com.java80.littlegame.common.db.entity.URoomInfo;

public class URoomInfoDaoCacheImpl implements URoomInfoDao {
	private URoomInfoDaoDBImpl rdb = null;

	@Override
	public List<URoomInfo> getAllByUserId(long userId) {
		Set<URoomInfo> set = CacheService.fuzzyKeys(
				CacheService.CACHEOBJPROFIX + URoomInfo.class.getSimpleName() + "-*-" + userId, URoomInfo.class);
		if (set != null && !set.isEmpty()) {
			return new ArrayList<>(set);
		} else {
			try {
				return rdb.getAllByUserId(userId);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public void insert(URoomInfo t) {
		try {
			rdb.insert(t);
			t.save();

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void delete(long id) {
		try {
			rdb.delete(id);
			CacheService.fuzzyKeysDel(CacheService.CACHEOBJPROFIX + URoomInfo.class.getSimpleName() + "-" + id + "-*");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void update(URoomInfo t) {
		// TODO Auto-generated method stub
		try {
			rdb.update(t);
			t.save();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public URoomInfo get(long id) {

		Set<URoomInfo> set = CacheService.fuzzyKeys(
				CacheService.CACHEOBJPROFIX + URoomInfo.class.getSimpleName() + "-" + id + "-*", URoomInfo.class);
		if (set != null && !set.isEmpty()) {
			return new ArrayList<>(set).get(0);
		} else {
			try {
				return rdb.get(id);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public void deletByUserId(long userId) {
		try {
			rdb.deletByUserId(userId);
			CacheService.fuzzyKeysDel(CacheService.CACHEOBJPROFIX + URoomInfo.class.getSimpleName() + "-*-" + userId);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public URoomInfoDaoCacheImpl(URoomInfoDaoDBImpl rdb) {
		super();
		this.rdb = rdb;
	}

}
